package com.qyxx.designer.miniweb.service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.qyxx.designer.modules.mapper.JaxbMapper;
import com.qyxx.designer.modules.utils.EncryptAndDecryptUtils;
import com.qyxx.jwp.bean.Module;

/**
 *  设计器Manager类
 *  
 *  @author gxj
 *  @version 1.0 2012-6-28 下午03:24:54
 *  @since jdk1.6
 */
@Component
public class DesignManager {

	private static Logger logger = LoggerFactory.getLogger(DesignManager.class);
	
	private JaxbMapper jaxb = new JaxbMapper(Module.class);
	
	public final static String ENCODING = "UTF-8";
	
	public final static String MODULE_PATH = "E:/space/eclipseSpace/idesigner/config/module/bill/";

	/**
	 * 保存module对象到xml文件
	 * @param module
	 */
	public void saveModule(Module module, String filePath) {
		String xml = jaxb.toXml(module, ENCODING);
		xml = EncryptAndDecryptUtils.aesEncrypt(xml, "");
		File file = new File(filePath + module.getModuleProperties().getKey() + ".xml");
		try {
			FileUtils.writeStringToFile(file, xml, ENCODING);
		} catch (IOException e) {
			throw new ServiceException("写文件时出现异常", e);
		}
	}
	
	/**
	 * 保存module对象到Json文件
	 * @param module
	 * @param filePath
	 */
	public void saveModuleJson(String moduleJson,Module module, String filePath) {

		File file = new File(filePath + module.getModuleProperties().getKey() + ".json");
		try {
			FileUtils.writeStringToFile(file, moduleJson, ENCODING);
		} catch (IOException e) {
			throw new ServiceException("写json文件时出现异常", e);
		}
	}
	
	
	
	/**
	 * 根据key读取xml文件转成module对象
	 * @param key
	 * @return
	 */
	public Module getModule(String key, String filePath) {
		try {
			File file = new File(filePath + key + ".xml");
			Module module = null;
			if(file.exists()) {
				String xml = FileUtils.readFileToString(file, ENCODING);
				xml = EncryptAndDecryptUtils.aesDecrypt(xml, "");
				module = jaxb.fromXml(xml);
			} else {
				module = new Module();
			}
			return module;
		} catch (IOException e) {
			throw new ServiceException("读文件时出现异常", e);
		} catch (Exception e) {
			throw new ServiceException("", e);
		}
	}
	
}
